<script setup lang="ts">
import {
  postFindMainList,
  getCode,
  postAddMain,
  postApproveMain
} from "@/api/procurement/procurementApi";
import { message } from "@/utils/message";

import Search from "./form/search.vue";
import { ref, onMounted, reactive } from "vue";
import type { PaginationProps, LoadingConfig, Align } from "@pureadmin/table";
import {
  ProcurementForm,
  AddProcurementForm,
  ApproveMainForm
} from "@/api/procurement/type/procurementForm";
import { ProcurementBackModel } from "@/api/procurement/type/procurementBackModel";
import { delay } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import forms, { type FormProps } from "./form/form.vue";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";
import { useDevice } from "@/utils/useDeviceDetect/useDeviceDetect";

defineOptions({
  name: "Inbound"
});
const { device } = useDevice();
/** 加载动画配置 */
const loadingConfig = reactive<LoadingConfig>({
  text: "正在加载第一页...",
  viewBox: "-10, -10, 50, 50",
  spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
  // svg: "",
  // background: rgba()
});
// 表格数据和加载状态
const tableData = ref<ProcurementBackModel[]>([]); /// 返回库存数据
const loading = ref(false); /// loading
const currentPage = ref(1);
const columns: TableColumnList = [
  {
    label: "序号",
    type: "index",
    align: "left"
  },
  {
    label: "单号",
    prop: "code",
    width: 180
  },
  {
    label: "订单状态",
    prop: "statusFlag",
    width: 100
  },
  {
    label: "供应商",
    prop: "supplierName"
  },
  {
    label: "总数",
    prop: "totalNum"
  },
  {
    label: "总金额",
    prop: "totalMoney"
  },
  {
    label: "打印次数",
    prop: "printFlag",
    width: 100
  },
  {
    label: "临时仓库",
    prop: "storeName",
    width: 100
  },
  {
    label: "临时货位",
    prop: "storeSiteName",
    width: 100
  },
  {
    label: "制单员",
    prop: "createName"
  },
  {
    label: "入库日期",
    prop: "createTime",
    width: 180
  },
  {
    label: "审批人",
    prop: "approveName"
  },
  {
    label: "提货车牌号",
    prop: "pickUpCarNum",
    width: 100
  },
  {
    label: "卸货方式",
    prop: "unloadingId",
    width: 100
  },
  {
    label: "备份",
    prop: "remark",
    width: 100
  },
  {
    label: "操作",
    width: 150,
    fixed: "right",
    slot: "operation"
  }
];

function onCurrentChange(val) {
  loadingConfig.text = `正在加载第${val}页...`;
  loading.value = true;
  delay(600).then(() => {
    loading.value = false;
  });
}
function onSizeChange(val) {
  console.log("onSizeChange", val);
}
/** 分页配置 */
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});
/// 表单载荷
const formData = ref<ProcurementForm>({
  arrivalId: null, // 到货方式
  code: "", // 到货单号
  endTime: null, // 结束时间
  pickUpCarId: null, // 取货车辆ID
  startTime: null, // 开始时间 时间戳
  statusFlag: null, // 订单状态 1草稿状态 2待入库 3已完成 4存档 5驳回 6已结算 ,
  supplierId: null, //供应商id
  sort: 0, // 排序方式 默认是0 创建时间排序，1 单号排序 ,
  sortType: -1, // 排序类型 默认是-1 倒序，1 正序 ,
  pageNum: 1, // 页码
  pageSize: 20 // 每页数量
});
// 处理搜索事件
const handleSearch = (params: any) => {
  const date = new Date(params.startTime);
  console.log(date.toLocaleString());
  // 重置到第一页
  currentPage.value = 1;
  // 合并查询参数
  const queryParams = {
    ...params
  };
  formData.value = queryParams;
  // 调用API获取数据
  postFindMainListFn();
};
// 结合Form表单（第二种方式）h 渲染函数 https://cn.vuejs.org/api/render-function.html#h
const addProcurementForm = ref<AddProcurementForm>({});
/// 添加新项的处理函数
// 这里可以实现添加新项的逻辑
const addItem = async (): Promise<Object> => {
  console.log("添加新项");
  const isHosOrderCode = await postCode(); // 获取订单编号
  if (isHosOrderCode) {
    addProcurementForm.value.code = storageLocal().getItem("orderCode") || "";
    let w = device.value.isMobile ? "80%" : "25%";
    addDialog({
      width: w,
      title: "增加",
      contentRenderer: () => forms,
      props: {
        // 赋默认值
        addProcurementForm: addProcurementForm.value
      },
      beforeSure: async (done, { options, index }) => {
        console.log(options, index);
        let formData = options.props.addProcurementForm;
        await addPro(formData);
        done(); // 需要关闭把注释解开即可
      }
    });
  }
  return;
};
/// 新增入库单
const addPro = async (addProForm: AddProcurementForm): Promise<any> => {
  try {
    // 调用登录API
    const back: BackModel = await postAddMain(addProForm);
    if (back.code == 1) {
      message(back.msg, { type: "success" });
    } else {
      message(back.msg, { type: "warning" });
    }
    storageLocal().removeItem("orderCode"); // 清除订单编号
    addProcurementForm.value = {};
    formData.value = {
      arrivalId: null, // 到货方式
      code: "", // 到货单号
      endTime: null, // 结束时间
      pickUpCarId: null, // 取货车辆ID
      startTime: null, // 开始时间 时间戳
      statusFlag: null, // 订单状态 1草稿状态 2待入库 3已完成 4存档 5驳回 6已结算 ,
      supplierId: null, //供应商id
      sort: 0, // 排序方式 默认是0 创建时间排序，1 单号排序 ,
      sortType: -1, // 排序类型 默认是-1 倒序，1 正序 ,
      pageNum: 1, // 页码
      pageSize: 20 // 每页数量
    };
    postFindMainListFn();
  } catch (error) {
    console.error("新增入库单失败:", error);
    message(`新增入库单失败：${error.msg}`, { type: "error" });
  }
};
// 获取订单编号
const postCode = async (): Promise<boolean> => {
  try {
    if (storageLocal().getItem("orderCode")) {
      console.log(`订单编号: ${storageLocal().getItem("orderCode")}`);
      return true;
    } else {
      // 调用登录API
      const { data }: BackModel = await getCode(formData.value);
      storageLocal().setItem("orderCode", data);
      console.log(`订单编号: ${data}`);
      return true;
    }
  } catch (error) {
    console.error("获取订单编号失败:", error);
    return false;
  }
};

/// 详情
const detailFn = async (row: ProcurementBackModel): Promise<void> => {
  try {
    // console.log(row);
    // let form: ApproveMainForm = {
    //   mainId: row.id, // 主表ID
    //   version: row.version // 版本号
    // };
    // // 调用登录API
    // const back: BackModel = await postApproveMain(form);
    // if (back.code == 1) {
    //   message(back.msg, { type: "success" });
    // } else {
    //   message(back.msg, { type: "warning" });
    // }
    message("详情功能尚未开放", { type: "warning" });
  } catch (error) {}
};
/// 编辑
const editRow = async (row: ProcurementBackModel): Promise<void> => {
  try {
    // console.log(row);
    // let form: ApproveMainForm = {
    //   mainId: row.id, // 主表ID
    //   version: row.version // 版本号
    // };
    // // 调用登录API
    // const back: BackModel = await postApproveMain(form);
    // if (back.code == 1) {
    //   message(back.msg, { type: "success" });
    // } else {
    //   message(back.msg, { type: "warning" });
    // }
    message("编辑功能尚未开放", { type: "warning" });
  } catch (error) {}
};
/// 改货位
const editStore = async (row: ProcurementBackModel): Promise<void> => {
  try {
    // console.log(row);
    // let form: ApproveMainForm = {
    //   mainId: row.id, // 主表ID
    //   version: row.version // 版本号
    // };
    // // 调用登录API
    // const back: BackModel = await postApproveMain(form);
    // if (back.code == 1) {
    //   message(back.msg, { type: "success" });
    // } else {
    //   message(back.msg, { type: "warning" });
    // }
    message("改货位功能尚未开放", { type: "warning" });
  } catch (error) {}
};
// 打印
const settlementFn = async (row: ProcurementBackModel): Promise<void> => {
  try {
    // console.log(row);
    // let form: ApproveMainForm = {
    //   mainId: row.id, // 主表ID
    //   version: row.version // 版本号
    // };
    // // 调用登录API
    // const back: BackModel = await postApproveMain(form);
    // if (back.code == 1) {
    //   message(back.msg, { type: "success" });
    // } else {
    //   message(back.msg, { type: "warning" });
    // }
    message("结算功能尚未开放", { type: "warning" });
  } catch (error) {}
};
// 打印
const printFn = async (row: ProcurementBackModel): Promise<void> => {
  try {
    // console.log(row);
    // let form: ApproveMainForm = {
    //   mainId: row.id, // 主表ID
    //   version: row.version // 版本号
    // };
    // // 调用登录API
    // const back: BackModel = await postApproveMain(form);
    // if (back.code == 1) {
    //   message(back.msg, { type: "success" });
    // } else {
    //   message(back.msg, { type: "warning" });
    // }
    message("打印功能尚未开放", { type: "warning" });
  } catch (error) {}
};
// 审核订单
const review = async (row: ProcurementBackModel): Promise<void> => {
  try {
    console.log(row);
    let form: ApproveMainForm = {
      mainId: row.id, // 主表ID
      version: row.version // 版本号
    };
    // 调用登录API
    const back: BackModel = await postApproveMain(form);
    if (back.code == 1) {
      message(back.msg, { type: "success" });
    } else {
      message(back.msg, { type: "warning" });
    }
  } catch (error) {
    console.error("审核订单失败:", error);
    message(`审核失败：${error.msg}`, { type: "error" });
  }
};

// 获取库存列表
const postFindMainListFn = async (): Promise<Object> => {
  try {
    loading.value = true;
    // 调用登录API
    const response: BackModel = await postFindMainList(formData.value);
    tableData.value = response.data; // 更新表格数据
    pagination.total = response.total; // 更新总数
    loading.value = false;
    // 返回登录结果
    return response;
  } catch (error) {
    // 处理错误
    throw error;
  }
};
// 页面加载时获取数据
onMounted(() => {
  postFindMainListFn();
});
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <component :is="Search" @search="handleSearch" @addItem="addItem" />
    </template>
    <template #default>
      <pure-table
        border
        row-key="id"
        alignWhole="center"
        showOverflowTooltip
        size="default"
        :loading="loading"
        :loading-config="loadingConfig"
        :height="440"
        :data="
          tableData.slice(
            (pagination.currentPage - 1) * pagination.pageSize,
            pagination.currentPage * pagination.pageSize
          )
        "
        :columns="columns"
        :pagination="pagination"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      >
        <template #operation="{ row }">
          <!-- 第三行：提货车牌 + 订单状态 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-button
                link
                type="primary"
                size="small"
                @click="detailFn(row)"
              >
                详情
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button link type="primary" size="small" @click="review(row)"
                >审核</el-button
              >
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-button link type="primary" size="small" @click="printFn(row)">
                打印
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button
                link
                type="primary"
                size="small"
                @click="settlementFn(row)"
                >结算</el-button
              >
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-button
                link
                type="primary"
                size="small"
                @click="editStore(row)"
                >改货位</el-button
              >
            </el-col>
            <el-col :span="12">
              <el-button link type="primary" size="small" @click="editRow(row)"
                >修改</el-button
              >
            </el-col>
          </el-row>
        </template>
      </pure-table>
    </template>
  </el-card>
</template>
